﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using shop.entity;
using shop.util;
using shop.service;
namespace shop.handler
{
    /// <summary>
    /// ImageUpload 的摘要说明
    /// </summary>
    public class UploadImageHandler : IHttpHandler
    {
        private ImageService imageService  = new ImageService();
     
        public void ProcessRequest(HttpContext context)
        {
            UploadImage(context);

        }
        private void UploadImage(HttpContext context) {
             HttpPostedFile  file=null;
            string json;
            try
            {
              file = context.Request.Files["file"];
            }
            catch (Exception e)
            {

                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, "选择要上传的图片"));
            }
            

            
            //后台也要对拿到的数据是否为图片进行校验（因为前台可以通过浏览器改代码，前台校验完了需要后台再拦截一下）
            var ext = Path.GetExtension(file.FileName);
            if (!(ext == ".jpeg" || ext == ".jpg" || ext == ".png" || ext == ".gif"))
            {
                context.Response.Write("shit,你传的不是图片");
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, "你传的不是图片"));
                context.Response.End();
            }
            else
            {
                //图片前缀
                string perfix = Guid.NewGuid().ToString().Substring(1, 12);
                //上传的文件保存到目录(为了保证文件名不重复，加个Guid)
                string path = "/web/resource/img/upload/" + perfix + file.FileName;
             
                
                file.SaveAs(context.Request.MapPath(path));//必须得是相对路径

                //把图片显示到前端让用户看得到
                string str = string.Format("<html><head></head><body><img src='{0}'/></body></html>",
                path);//必须得是绝对路径！！！！
                Image image = new Image()
                {
                    ImagePath = "/upload/" + perfix + file.FileName,
                    Name = file.FileName,
                };
                int id=0;
                try
                {
                  id = imageService.Add(image);
                }
                catch (Exception e)
                {
                    json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1,e.Message));
                   
                }

                image.Id = id;
              
                json = JsonUtil.getJsonString(JsonResult<Image>.RenderSuccess(image));

            }

            context.Response.Write(json);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}